/**
 * Created by chenzp on 18-7-27.
 */
layui.use(['jquery', 'layer', 'table', 'form', 'ly', 'utl'], function () {

    var $ = layui.$
    var utl = layui.utl

    var tokenSctrip = {
        $aform: $('#aForm')
        , $sform: $('#sForm')

        , $htmlB: $('#htmlBlock')

        //请求地址
        , url: {
            add: '/analyzer/character/add'
            , list: '/analyzer/character/list'
            , id: function (id) {
                return `/analyzer/character/${id}`
            }
        }

        //主函数
        , main: function () {

            $('#a_c_t_btn').openLy('a_t_a_from', 'click', {area: '1000*500', title: '新增'})
            this.initTable()
            this.initEvent()
        }

        //初始化事件
        , initEvent: function () {
            var $this = this
            layui.form.on('select(tokenType)', function (data) {
                layui.form.render()
            })
        }

        //初始化表格
        , initTable: function () {

            this.table = layui.table.render({
                elem: '#a_c_table'
                , url: this.url.list
                , cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                , page: true //开启分页
                , loading: true//是否显示加载条
                , where: utl.serializeJson(this.$sform)
                , cols: [
                    [
                        {type: 'checkbox'}
                        , {field: 'id', title: 'ID', sort: true}
                        , {field: 'name', title: '名称'}
                        , {
                        field: 'characterType', title: '类型', sort: true, templet: function (d) {
                            return d.characterType == 'html_strip' ? 'HTML过滤器' : d.characterType == 'mapping' ? 'mappings过滤器' : '正则过滤器'
                        }
                    }
                        , {field: 'value', title: '值'}
                        , {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 115}
                    ]

                ]

            })
        }

        //类型值切换
        , upateTokenTypeVal: function (type) {
            var models = {

                //Stemmer Override
                stemmer_override: [
                    {
                        label: '词干映射'
                        , type: 'mapping'
                        , placeholder: '原词干,修改后词干'
                        , value: 'rules'
                    }
                ],

                //英文小写
                lowercase: [],

                //英文大写
                uppercase: [],

                //分割词
                delimited_payload: [
                    {
                        label: '截断符号'
                        , type: 'input'
                        , placeholder: '请输入截断符号'
                        , value: 'delimiter'
                    }
                ],

                // 长度词
                length: [
                    {
                        label: '最小长度'
                        , type: 'input'
                        , placeholder: '请输入数值'
                        , value: 'min'
                    },

                    {
                        label: '最大长度'
                        , type: 'input'
                        , placeholder: '请输入数值'
                        , value: 'max'
                    }
                ],

                //近义词
                synonym: [
                    {
                        label: '近义词'
                        , type: 'synonym'
                        , placeholder: '请输入近义词'
                        , value: 'synonyms'
                    }
                ],

                //停止符
                stop: [
                    {
                        label: '停止词'
                        , type: 'multi'
                        , placeholder: '请输入停止词'
                        , value: 'stopwords'
                    }
                ],

                //限制
                limit: [
                    {
                        label: '不限定token数量'
                        , type: 'radio'
                        , value: 'consume_all_tokens'
                    },
                    {
                        label: 'token数量'
                        , type: 'input'
                        , placeholder: '请输入限定token数量'
                        , value: 'max_token_count'
                    }
                ],

                //截断
                truncate: [
                    {
                        label: '截断符'
                        , type: 'input'
                        , placeholder: '请输入截断符'
                        , value: 'length'
                    }
                ],

                //保留字
                keep: [
                    {
                        label: '保留字'
                        , type: 'multi'
                        , placeholder: '请输入保留字'
                        , value: 'keep_words'
                    }
                ],

                //唯一性
                unique: [
                    {
                        label: '是否相同位置token'
                        , type: 'radio'
                        , value: 'only_on_same_position'
                    }
                ],
                //正则模式匹配
                pattern_capture: [
                    {
                        label: '正则匹配'
                        , type: 'multi'
                        , placeholder: '正则表达式'
                        , value: 'patterns'
                    },
                    {
                        label: '保持原始令牌'
                        , type: 'radio'
                        , value: 'preserve_original'
                    }

                ]


            }
        }

        // //初始化各类型下拉框
        // ,initSeleType:function () {
        //     var $this = this
        //     var $model = $('.type-model')
        //
        //     for(var i=0;i<$model.length;i++){
        //         var $ele = $model.eq(i)
        //         if($ele.hasClass('multi-type')) {
        //             //多输入框
        //             $ele.find('input').on('focusout', function () {
        //                 var $btn = $this.addHtmlBtnStore($(this).val())
        //                 if (!$btn) return
        //                 $(this).before($btn)[0].focus()
        //                 $(this).val('')
        //             })
        //         }
        //     }
        // }

        //初始化多选框
        , initMutli: function () {

            var $model = $('.multi-type.type-model')
            var $this = this

            $model.find('input').on('focusout', function () {
                var val = $(this).val()
                if (val.trim()) {
                    layer.msg('输入值不能为空')
                    return
                }

                val = val.trim()

                var mutliStore = $this.mutliStore ? $this.mutliStore : []


                if ($.inArray(val.trim(), mutliStore) != -1) {
                    layer.msg('存在相同值')
                    return
                }

                var $btn = $(`<button type="button" class="layui-btn layui-bt n-sm">${val}<b>x</b></button>`)

                mutliStore.push(val)

                $this.mutliStore = mutliStore

                $btn.find('b').on('click', function () {
                    $this.mutliStore.splice($.inArray(val, $this.mutliStore), 1);
                    $btn.remove()
                })
            })
        }

        //初始化mapping组件
        , initMapping: function () {

            var $model = $('.mappping-type.type-model')
            var $this = $(this)

            var html_rep = `<div class="row" style="height: 37px;">
                                <input type="text"  autocomplete="off" placeholder="原值" class="layui-input mapping-tag">
                                <span class="mapping-tag">=></span>
                                <input type="text"  autocomplete="off" placeholder="新值" class="layui-input mapping-tag">
                               <button type="button" class="layui-btn layui-btn-sm" style="margin-left: 20px;">―</button>
                            </div>`

            $model.find('button').on('click', function () {

                var $html = $(html_rep)

                $html.find('input').on('focusout change', function () {

                    var index = $(this).index()

                    if(index == 0) {
                        var val = $(this).val().trim()
                        if (!val) {
                            layer.msg('值不能为空')
                            return
                        }

                        if (mappingStoreFn.existKey(val)) {
                            layer.msg('存在一样的值')
                            $(this).val('')
                            $(this)[0].focus()
                            return
                        }

                    }
                    mappingStoreFn.inserUpdateData($(this))
                })


                $html.find('button').on('click', function () {
                    mappingStoreFn.removeData($(this))
                    $html.remove()
                })

                $(this).parent().before($html)
            })


            var mappingStoreFn = {


                getStore: function () {
                    $this.mappingStore = $this.mappingStore ? $this.mappingStore : {store: [], targets: []}
                }

                , inserUpdateData: function ($input) {
                    var $target = $input.parent()
                    var index = $input.index()

                    var isInsert = true
                    for (var i = 0; i < this.getStore().targets.length; i++) {
                        var target = this.getStore().targets[i]
                        if ($target.is(target.target)) {

                            if (index == 0) {
                                target.key = $input.val().trim()
                            } else {
                                target.value = $input.val().trim()
                            }

                            this.setStoreVal()

                            isInsert = false
                            break
                        }
                    }

                    if (isInsert) {
                        var key = $target.find('input.eq(0)').val().trim()
                        var value = $target.find('input.eq(1)').val().trim()

                        if(key && value) {
                            this.mappingStore.store.push(`${key} => ${value}`)
                        }

                        this.mappingStore.targets.push({
                            target: $target
                            , key: key
                            , value: value
                        })

                    }

                }

                , setStoreVal: function () {

                    var arr = new Array()
                    for (var i = 0; i < $this.mappingStore.targets.length; i++) {
                        var target = $this.mappingStore.targets[i]

                        if(target.key && target.value) {
                            arr.push(`${target.key} => ${target.value}`)
                        }
                    }

                    $this.mappingStore.store = arr
                }

                , removeData: function ($target) {
                    var $parent = $target.parent()

                    for (var i = 0; i < this.getStore().targets.length; i++) {
                        var target = this.getStore().targets[i]
                        if ($parent.is(target.target)) {
                            $this.mappingStore.targets.splice(i, 1)
                            this.setStoreVal()
                            break
                        }
                    }
                }

                //是否存在
                , existKey: function (key) {
                    for (var i = 0; i < this.getStore().targets.length; i++) {
                        var target = this.getStore().targets[i]
                        if(key == target.key) {
                            return true
                        }
                    }

                    return false
                }
            }


        }



    }

    tokenSctrip.main()
})
